﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace HiCore.WebApi.Example.DbContexts.Encryption
{
    public class MD5Utility
    {
        /// <summary>
        /// MD5 32位加密 加密后密码为小写
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string CreateMD5Lower32(string text)
        {
            var bts = Encoding.UTF8.GetBytes(text);
            using (var m = MD5.Create())
            {
                var result = m.ComputeHash(bts);
                return BitConverter.ToString(result).Replace("-", "").ToLower();
            }
        }

        /// <summary>
        /// MD5 16位加密 加密后密码为小写
        /// </summary>
        /// <param name="ConvertString"></param>
        /// <returns></returns>
        public static string CreateMD5Lower16(string text)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(text)), 4, 8);
            t2 = t2.Replace("-", "");

            t2 = t2.ToLower();

            return t2;
        }

        public static string CreateMD5(Stream fileStream)
        {
            fileStream.Position = 0;
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(fileStream);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();
        }
    }
}
